<?php

namespace App\Imports;

use App\Rules\Mobile;
use App\User;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\SkipsErrors;
use Maatwebsite\Excel\Concerns\SkipsFailures;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithBatchInserts;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Validators\Failure;

class UsersImport implements ToModel, WithHeadingRow, WithValidation, WithBatchInserts, SkipsOnFailure, SkipsOnError
{
    use Importable, SkipsFailures, SkipsErrors;

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            //
            'mobile'=>(string)$row['mobile']
        ]);
    }

//    public function headingRow(): int
//    {
//        return 1;
//    }

    public function rules(): array
    {
        return [
            'mobile' => ['required',new Mobile, function($attribute, $value, $onFailure){
                if(User::query()->where(['mobile'=>$value])->get()->toArray()){
                    $onFailure('手机号码已存在');
                }
            }],
        ];
    }

    public function batchSize(): int
    {
        return 100;
    }


//    public function onFailure(Failure ...$failures)
//    {
//        // Handle the failures how you'd like.
//    }
}
